﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sasa.QualityTools.CodeAnalysis.Core.Properties;
using Sasa.QualityTools.CodeAnalysis.Common;
using System.Text.RegularExpressions;
using Sasa.QualityTools.CodeAnalysis.Core.Utilities;

namespace Sasa.QualityTools.CodeAnalysis.Core.Models
{
    public class CodeMetricsCalculator : CodeAnalyzerBase<MetricsReport, MetricsErrorCodes>
    {
        protected override void ResolveMissingAssemblies()
        {
            var errors = new List<CodeAnalysisError>();
            foreach (var msg in CommandMessagesCache.Where(o => o.Category == CommandMessage.MessageCategory.Error))
            {
                var id = Regex.Match(msg.Content, @"^.+? : (CA\d{4}) :").Groups[1].Value;
                errors.Add(new CodeAnalysisError { Id = id, Message = msg.Content });
            }

            var resolver = new MissingAssemblyResolver(MissingAssembliesCachePath, ReferenceAssemblyPaths);
            resolver.Resolve(errors);
        }

        protected override MetricsErrorCodes Convert(int commandExitCode)
        {
            return (MetricsErrorCodes)commandExitCode;
        }

        protected override bool HasAssemblyReferencesError(MetricsErrorCodes result)
        {
            return result.HasFlag(MetricsErrorCodes.AssemblyReferencesError);
        }

        protected override bool HasAnalysisError(MetricsErrorCodes result)
        {
            return result.HasFlag(MetricsErrorCodes.AnalysisError);
        }

        protected override string GetReportPath()
        {
            return Regex.Match(CommandOption, @"/o:""(.+?)""").Groups[1].Value;
        }
    }
}
